// pages/posts/post.js
var util = require('../../utils/util.js'); 
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    hidden: false,
    listInfo: {},
    bannerList: {},
    picker1Value: 0,
    picker1Range: ['国三', '国四', '国五'],
    timeValue: '08:08',
    dateValue: '2018-10',
    dateValues: '2018-10',
    region: ['广东省', '广州市', '海珠区'],
    customItem: '全部',
    checolors: '0',
    checolor: ['黑', '白', '红', '蓝', '灰', '银白', '银灰', '粉红', '天蓝', '香槟'],
    baoxiansj:'0',
    baoxian: ['无','2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031', '2032', '2033', '2034', '2035', '2036', '2037', '2038', '2039', '2040', '2041', '2042', '2043', '2044', '2045', '2046', '2047', '2048', '2049', '2050', '2051', '2052', '2053', '2054', '2055', '2056', '2057', '2058'],
    productInfo: {
      bannerInfo: [],
      weixinInfo: []
    },

    bannerInfoUrl: [],
    weixinInfoUrl: [],

    register: {
      money: '',
      type: '',
      actual_mileage: '',
      describe: '',
      phone: '',
      color: '',
      guide_price: '',
      configuration: '',
      displacement: '',
      insurance_time: '',
      transfer: '',
      key_num: '',
      maintain_record: '',
      after_mileage:''
    },
    uid: 0,
    is_license: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //that._refreshData();

    var time = util.formatDateTime(new Date());

    that.setData({
      dateValue: time.substring(0,7),
      dateValues:time.substring(0,7)
    });

    //获取当前位置
    that.getLocation();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  _refreshData: function () {
    var that = this;
    that.setData({
      uid: wx.getStorageInfoSync('uid') ? wx.getStorageInfoSync('uid'): getApp().globalData.uid
    })
    console.log('刷新了:uid' + getApp().globalData.uid);
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分--享
   */
  onShareAppMessage: function () {

  },

  normalPickerBindchange: function (e) {
    this.setData({
      picker1Value: e.detail.value
    })
  },
  timePickerBindchange: function (e) {
    this.setData({
      timeValue: e.detail.value
    })
  },
  datePickerBindchange: function (e) {
    this.setData({
      dateValue: e.detail.value
    })
  },
  datePickerBindchanges: function (e) {
    this.setData({
      dateValues: e.detail.value
    })
  },
  // 地址
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  baoxians: function (e) {
    this.setData({
      baoxiansj: e.detail.value
    })
  },
  colorss: function (e) {
    this.setData({
      checolors: e.detail.value
    })
  },

  bindChooiceProduct: function (e) {
    var that = this;
    var type = e.target.dataset.type;
    var num = 9
    console.log(that.data.productInfo.bannerInfo);

    if (type == 1) {
      var have_num = that.data.productInfo.bannerInfo.length;
      if (have_num > 8) {
        wx.showToast({
          title: '最多上传9张',
          icon: 'success',
          mask: true
        })
        return;
      }
    } else {
      num = 1;
      var have_num = that.data.productInfo.weixinInfo.length;
      if (have_num > 0) {
        wx.showToast({
          title: '最多上传1张',
          icon: 'success',
          mask: true
        })
        return;
      }
    }

    wx.chooseImage({
      count: num - have_num, //最多可以选择的图片总数  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })
        var uploadImgCount = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          wx.uploadFile({
            url: getApp().d.hostUrl +'api/Upload/image',
            filePath: tempFilePaths[i],
            name: 'image',
            formData: {
              'imgIndex': i
            },
            header: {
              "Content-Type": "multipart/form-data",
              'mchnt': getApp().d.mchnt
            },

            success: function (res) {
              console.log('上传图片 => ' + res);
              if (type == 1) {
                var have_num = that.data.productInfo.bannerInfo.length;
                if (have_num > 8) {
                  wx.showToast({
                    title: '最多上传9张',
                    icon: 'success',
                    mask: true
                  })
                  return;
                }
              } else {
                num =1;
                var have_num = that.data.productInfo.weixinInfo.length;
                if (have_num > 0) {
                  wx.showToast({
                    title: '最多上传1张',
                    icon: 'success',
                    mask: true
                  })
                  return;
                }
              }

              uploadImgCount++;
              var data = JSON.parse(res.data);
              //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }

              var productInfo = that.data.productInfo;
              var bannerInfoUrl = that.data.bannerInfoUrl;
              var weixinInfoUrl = that.data.weixinInfoUrl;

              if (type == 1) {
                if (productInfo.bannerInfo == null) {
                  productInfo.bannerInfo = [];
                }
                productInfo.bannerInfo.push({
                  "url": data.data
                });
                if (bannerInfoUrl == null) {
                  bannerInfoUrl = [];
                }
                bannerInfoUrl.push(data.data);
              } else {
                if (productInfo.weixinInfo == null) {
                  productInfo.weixinInfo = [];
                }
                productInfo.weixinInfo.push({
                  "url": data.data
                });
                if (weixinInfoUrl == null) {
                  weixinInfoUrl = [];
                }
                weixinInfoUrl.push(data.data);
              }

              that.setData({
                productInfo: productInfo,
                weixinInfoUrl: weixinInfoUrl,
                bannerInfoUrl: bannerInfoUrl
              });

              console.log(that.data);
              //如果是最后一张,则隐藏等待中  
              if (uploadImgCount == tempFilePaths.length) {
                wx.hideToast();
              }
            },
            fail: function (res) {
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) { }
              })
            }
          });
        }
      }
    });
  },

  //表单提交按钮
  formSubmit: function (e) {
    var that = this;
    console.log('form发生了submit事件，携带数据为：', e)

    var formData = e.detail.value;
    var uid = wx.getStorageSync('uid');
    console.log('缓存中的uid:'+uid);

    formData.uid = uid;
    formData.images = that.data.bannerInfoUrl;
    formData.weixin_images = that.data.weixinInfoUrl;
    formData.is_license = that.data.is_license ? 1 : 0;
    formData.discharge_type = that.data.picker1Range[that.data.picker1Value];
    formData.insurance_time = that.data.baoxian[that.data.baoxiansj];
    //formData.color = that.data.checolor[that.data.checolors];
    console.log('formData:' + formData);

    if (!uid || uid == '' || uid<=0) {
      app.login();
    }

    if (!formData.money || formData.money == '' || formData.money <=0 ) {
      wx.showModal({
        title: '提示', 
        showCancel: false,
        content: '批发价格不正确',
      })
      return;
    }

    if (!formData.type || formData.type==''){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车型不能为空',
      })
      return;
    }

    if (!formData.actual_mileage || formData.actual_mileage == '' || formData.money < 0) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '实际里程不正确',
      })
      return;
    }

    if (!formData.describe || formData.describe == '' ) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车况描述不能为空',
      })
      return;
    }

    if (!formData.phone || formData.phone == '' || formData.phone.length!=11) {
      wx.showModal({
        title: '提示',
        content: '联系电话不正确',
        showCancel: false
      })
      return;
    }

    if (!formData.color || formData.color == '' ) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '车体颜色不正确',
      })
      return;
    }

    wx.request({
      url: app.d.hostUrl + 'api/car/save',
      data: formData,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'mchnt': getApp().d.mchnt 
      },

      success: function (res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.message,
            success: function (r) {
              console.log(r);

              that.setData({
                register: null,
                productInfo: null,
                picker1Value: 0,
                picker1Range: ['国三', '国四', '国五'],
                timeValue: '08:08',
                dateValue: util.formatDateTime(new Date()),
                dateValues: util.formatDateTime(new Date()),
                region: ['广东省', '广州市', '海珠区'],
                customItem: '全部',
                checolors:0,
                baoxiansj:0,
                'productInfo.bannerInfo':[],
                'productInfo.weixinInfo':[],
                bannerInfoUrl:[],
                weixinInfoUrl: []
              });
              wx.switchTab({
                url: '../cms/index',
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2000
          });
        }
      },

      fail: function () {
        // fail
        wx.showToast({
          title: '网络请求异常',
          duration: 2000
        });
      }
    });

  },

  //删除图片
  delImage: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    var type = e.target.dataset.type;
    var productInfo = that.data.productInfo;
    var weixinInfoUrl = that.data.weixinInfoUrl;
    var bannerInfoUrl = that.data.bannerInfoUrl;
    wx.showModal({
      title: '提示',
      content: '确认要删除此照片吗?',
      success: function (res) {
        if (res.confirm) {
          console.log(productInfo);
          if (type == 1) {
            if (productInfo.bannerInfo != null) {
              productInfo.bannerInfo.splice(index, 1)
              bannerInfoUrl.splice(index, 1);
              that.setData({
                productInfo: productInfo,
                bannerInfoUrl: bannerInfoUrl
              });
            }
          } else {
            if (productInfo.weixinInfo != null) {
              productInfo.weixinInfo.splice(index, 1)
              weixinInfoUrl.splice(index, 1);
              that.setData({
                productInfo: productInfo,
                weixinInfoUrl: weixinInfoUrl
              });
            }
          }

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var is_license = (e.detail.value == 1) ? true : false;
    var that = this;
    that.setData({
      is_license: is_license
    })
  },


  //获取地图
  getLocation: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84', 
      success: function (res) {
        // success    
        var longitude = res.longitude
        var latitude = res.latitude
        that.loadCity(longitude, latitude)
      }
    })
  }, 


  //获取当前位置信息
  loadCity: function (longitude, latitude) {
    var page = this
    page.setData({ region: ['江苏省', '镇江市', '润州区'] });
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=AWElrsAvW0PKvANfW6suOI0NfWDAtNXH&location=' + latitude + ',' + longitude + '&output=json',
      data: {},
      header: {
        'Content-Type': 'application/json',
        'mchnt': getApp().d.mchnt 
      },
      success: function (res) {
        // success    
        console.log(res);
        var city = res.data.result.addressComponent.city;
        var province = res.data.result.addressComponent.province;
        var district = res.data.result.addressComponent.district;
        page.setData({ region: [province, city, district] });
      },
      fail: function () {
        page.setData({ currentCity: "获取定位失败" });
      },
    })
  },


  getInfo:function(){
    var that = this;
    wx.checkSession({
      success: function (res) {
        //session_key 未过期，并且在本生命周期一直有效
        console.log(res);
        var uid = wx.getStorageSync('uid');
        var openid = wx.getStorageSync('openid');
        that.globalData.uid = uid;
        that.globalData.openid = openid;
      },
      fail: function () {
        // 登录
        wx.login({
          success: res => {
            //发送 res.code 到后台换取 openId, sessionKey, unionId
            wx.request({
              //获取openid接口  
              url: getApp().d.hostUrl +'api/car/get_session_key',
              data: {
                js_code: res.code,
                grant_type: 'authorization_code'
              },
              header: { 'mchnt': getApp().d.mchnt },
              method: 'POST',
              success: function (res) {
                console.log(res);

                if (res.data.code == 1) {

                  console.log(res.data)

                  wx.setStorageSync('uid', res.data.data.uid);
                  wx.setStorageSync('openid', res.data.data.openid);
                  getApp().globalData.uid = res.data.data.uid;
                  getApp().globalData.openid = res.data.data.openid;
                  //获取用户信息
                  wx.getSetting({
                    success: res => {
                      if (res.authSetting['scope.userInfo']) {
                        console.log('已授权')
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        wx.getUserInfo({
                          success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            getApp().globalData.userInfo = res.userInfo

                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                              this.userInfoReadyCallback(res)
                            }
                          }
                        })
                      } else {
                        console.log('未授权')
                      }
                      //console.log(this.globalData.userInfo);
                    }
                  })
                } else {
                  wx.showToast({
                    title: res.data.message,
                  })
                  return;
                }
              }
            })
          }
        })
      }
    })
  }
})
